package com.bjgzy.rating.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bjgzy.rating.R;
import com.bjgzy.rating.R2;
import com.bjgzy.rating.di.component.DaggerEntriesDetailComponent;
import com.bjgzy.rating.mvp.contract.EntriesDetailContract;
import com.bjgzy.rating.mvp.presenter.EntriesDetailPresenter;
import com.bjgzy.rating.mvp.ui.fragment.AudioPlayFragment;
import com.bjgzy.rating.mvp.ui.fragment.DocumentFragment;
import com.bjgzy.rating.mvp.ui.fragment.PictureFragment;
import com.bjgzy.rating.mvp.ui.fragment.VideoFragment;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.EntriesData;
import com.eduhzy.ttw.commonsdk.entity.EntriesDetailData;
import com.eduhzy.ttw.commonsdk.entity.RatingHomeData;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoRelativeLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-8-8 9:50:00
 */
@Route(path = RouterHub.RATING_ENTRIESDETAILACTIVITY)
public class EntriesDetailActivity extends BaseActivity<EntriesDetailPresenter> implements EntriesDetailContract.View {
    BaseFragment fragment;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_vote)
    TextView tvVote;
    @BindView(R2.id.tv_level)
    TextView tvLevel;
    @BindView(R2.id.btn_vote)
    QMUIRoundButton btnVote;
    @BindView(R2.id.btn_submit)
    QMUIRoundButton btnSubmit;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;
    @BindView(R2.id.layout_vote)
    ViewGroup mLayoutVote;
    @BindView(R2.id.layout_submit)
    ViewGroup mLayoutSubmit;

    @Autowired(name = Constants.ROUTER_BOOLEAN)
    boolean modify;
    @Autowired(name = Constants.ROUTER_DATA)
    EntriesData data;
    @Autowired(name = Constants.ROUTER_BOOLEAN2)
    boolean isAward;
    @BindView(R2.id.public_toolbar_iv_right)
    ImageView mPublicToolbarIvRight;
    @BindView(R2.id.public_toolbar_right_iv_layout)
    AutoRelativeLayout mPublicToolbarRightIvLayout;
    private EntriesDetailData mEntriesDetailData;
    private EntriesDetailData mData;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerEntriesDetailComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.rating_activity_entries_detail;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        btnVote.setChangeAlphaWhenPress(true);
        if (modify) {
            mLayoutVote.setVisibility(View.GONE);
//            mLayoutSubmit.setVisibility(View.VISIBLE);
        } else {
            mLayoutVote.setVisibility(View.VISIBLE);
//            mLayoutSubmit.setVisibility(View.GONE);
            if (isAward) {
                tvLevel.setVisibility(View.VISIBLE);
                btnVote.setEnabled(false);
                btnVote.setText("活动已结束");
            } else {
                btnVote.setEnabled(true);
            }
        }

        mPresenter.getWorksById(data.getWorksId());


    }

    @Override
    public void showLoading() {
        mEmptyView.show(true);
    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void update(EntriesDetailData data) {
        this.mEntriesDetailData = data;
        if (data.getUserRight().getCouldVote() == 1) {
            btnVote.setEnabled(true);
        } else {
            btnVote.setEnabled(false);
        }
        if (data.getUserRight().getCouldUpdate() == 1) {
            mLayoutSubmit.setVisibility(View.VISIBLE);
        } else {
            mLayoutSubmit.setVisibility(View.GONE);
        }
        if (ObjectUtils.isNotEmpty(data.getShareLink())) {
            mPublicToolbarRightIvLayout.setVisibility(View.VISIBLE);
            mPublicToolbarIvRight.setImageResource(R.drawable.icon_share);
            this.mData = data;
        }


        tvLevel.setText(Constants.AWARD[data.getAwardLevel()]);
        tvTitle.setText(data.getWorksName());
        tvName.setText(data.getUnionName() + " (" + data.getUnionUnit() + ")");
        tvTime.setText(TimeUtils.millis2String(data.getCreateTime(), new SimpleDateFormat("yyyy-MM-dd")));
        tvVote.setText(String.valueOf(data.getVoteCount()));
        //文件格式 0：通用类，1，视频类，2：文档类，3：图片类，4：音频类5压缩文件(YXS：6我的资源 7我的备课 )
        if (ObjectUtils.isNotEmpty(data.getAttachmentList())) {
            for (EntriesDetailData.AttachmentListBean attachmentListBean : data.getAttachmentList()) {
                attachmentListBean.setImg(data.getImg());
            }

            switch (data.getFileType()) {
                case Constants.FILETYPE.VIDEO:
                    fragment = VideoFragment.newInstance();
                    fragment.setData(data.getAttachmentList());
                    break;
                case Constants.FILETYPE.DOCUMENT:
                    fragment = DocumentFragment.newInstance();
                    fragment.setData(data.getAttachmentList());
                    break;
                case Constants.FILETYPE.PICTURE:
                    fragment = PictureFragment.newInstance();
                    fragment.setData(data.getAttachmentList());
                    break;
                case Constants.FILETYPE.AUDIO:
                    fragment = AudioPlayFragment.newInstance();
                    fragment.setData(data.getAttachmentList());
                    break;
                default:

                    break;
            }
        } else {
            //显示空内容
            fragment = PictureFragment.newInstance();
            fragment.setData(new ArrayList<EntriesDetailData.AttachmentListBean>());
        }
        if (ObjectUtils.isNotEmpty(fragment)) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, fragment);
            transaction.commit();
        }
        mEmptyView.hide();
    }

    @Override
    public void loadFail() {
        if (ObjectUtils.isNotEmpty(mEmptyView)) {
            mEmptyView.show(
                    false,
                    getResources().getString(R.string.public_emptyView_mode_desc_fail_title),
                    null,
                    getResources().getString(R.string.public_emptyView_mode_desc_retry),
                    v -> {
                        mPresenter.getWorksById(data.getWorksId());
                    });

        }
    }

    @Override
    public void onBackPressed() {
        if (fragment != null && fragment instanceof VideoFragment && ((VideoFragment) fragment).onBackPressed()) {
            return;
        }
        finish();
    }


    @OnClick({R2.id.btn_vote, R2.id.btn_submit, R2.id.public_toolbar_right_iv_layout})
    public void onViewClicked(View v) {
        if (v.getId() == R.id.btn_vote) {
            MobclickAgent.onEvent(getActivity(), "ttw_rating_vote");
            mPresenter.saveVote(data.getWorksId());
        } else if (v.getId() == R.id.public_toolbar_right_iv_layout) {
            Message msg = Message.obtain();
            msg.what = EventBusTags.SHOW_SHARE;
            msg.obj = mData;
            EventBus.getDefault().post(msg, RouterHub.APP_HOMEACTIVITY);

        } else if (v.getId() == R.id.btn_submit) {
            if (data.getFileType() == Constants.FILETYPE.DOCUMENT) {
                showMessage("手机端不支持修改此类型活动");
            } else {
                RatingHomeData ratingHomeData = new RatingHomeData();
                ratingHomeData.setWorksId(data.getWorksId());
                ratingHomeData.setId(data.getResearchId());

                ARouter.getInstance()
                        .build(RouterHub.RATING_SIGNUP1ACTIVITY)

                        .withString(Intent.EXTRA_TITLE, Constants.CHOOSEGROUP)
                        .withParcelable(Constants.ROUTER_DATA, ratingHomeData)
                        .withParcelable(Constants.PARCELABLE_DATA, mEntriesDetailData)
                        .navigation();

            }
        }
    }

    @Subscriber(tag = RouterHub.RATING_ENTRIESDETAILACTIVITY)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.WORKS_UPLOAD_SUCCESS:
                killMyself();
                break;
            case EventBusTags.WORKS_UPLOAD_SUCCESS_WITHOUT_FILE:
                mPresenter.getWorksById(data.getWorksId());
                break;
            default:
        }
    }

}
